import os
import json
from typing import Dict, Any
import logging

logger = logging.getLogger(__name__)

class ConfigManager:
    """配置管理器 - 负责管理应用配置和规则"""
    
    def __init__(self, config_dir: str = 'config'):
        self.config_dir = config_dir
        self.rules_file = os.path.join(config_dir, 'rules.json')
        self.app_config_file = os.path.join(config_dir, 'app_config.json')
        self.ensure_config_dir()
        self.load_app_config()
    
    def ensure_config_dir(self):
        """确保配置目录存在"""
        os.makedirs(self.config_dir, exist_ok=True)
    
    def load_app_config(self):
        """加载应用配置"""
        default_config = {
            'max_file_size': 16 * 1024 * 1024,  # 16MB
            'upload_folder': 'uploads',
            'temp_folder': 'temp',
            'allowed_extensions': ['.tar.gz'],
            'log_level': 'INFO'
        }
        
        try:
            if os.path.exists(self.app_config_file):
                with open(self.app_config_file, 'r', encoding='utf-8') as f:
                    self.app_config = json.load(f)
                    # 合并默认配置
                    for key, value in default_config.items():
                        if key not in self.app_config:
                            self.app_config[key] = value
            else:
                self.app_config = default_config
                self.save_app_config()
        except Exception as e:
            logger.error(f"加载应用配置失败: {e}")
            self.app_config = default_config
    
    def save_app_config(self):
        """保存应用配置"""
        try:
            with open(self.app_config_file, 'w', encoding='utf-8') as f:
                json.dump(self.app_config, f, ensure_ascii=False, indent=2)
        except Exception as e:
            logger.error(f"保存应用配置失败: {e}")
    
    def get_config(self, key: str, default: Any = None) -> Any:
        """获取配置值"""
        return self.app_config.get(key, default)
    
    def set_config(self, key: str, value: Any):
        """设置配置值"""
        self.app_config[key] = value
        self.save_app_config() 